import store2 from "store2";
import { request } from "@/utils/request.ts";

const initialState = {
  token: store2.get("token") || "", // 用户token
  info: null as API.CurrentUser | null, // 用户信息
  menus: [] as API.MenuObject[], // 用户的菜单权限
  permissions: [] as string[], // 用户的按钮权限
};

// 异步动作，获取用户信息
export const getInfo = async (dispatch: any) => {
  // 获取用户信息
  const resp = await request.get<{
    info: API.CurrentUser;
    menus: API.MenuObject[];
  }>("/admin/base/comm/personInfo");
  // 将 resp 写入到 state 中，派发一个普通动作
  dispatch({ type: "SET_INFO", payload: resp });
};

export const reducer = (state = initialState, action: any) => {
  switch (action.type) {
    case "LOGIN":
      return {
        ...state,
        token: action.payload.token,
      };
    case "SET_INFO":
      return {
        ...state,
        info: action.payload.info as API.CurrentUser,
        menus: action.payload.menus as API.MenuObject[],
        permissions: action.payload.menus
          .filter((item: any) => item.type === 2)
          .map((item: any) => item.perms),
      };
    default:
      return state;
  }
};
